package ti.me.seek2chat.activities

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.provider.MediaStore
import android.util.Base64
import android.util.Patterns
import android.view.View.GONE
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import ti.me.seek2chat.databinding.ActivitySignUpBinding
import ti.me.seek2chat.leancloud.LeanCloudService
import ti.me.seek2chat.utilities.Constants
import ti.me.seek2chat.utilities.PreferenceManager
import java.io.ByteArrayOutputStream
import java.io.FileNotFoundException

/**
 * SignUpActivity 是一个处理用户注册的活动类。
 *
 * 在这个活动中，用户可以输入他们的注册信息并提交。提交后，应用会启动一个新的任务并清除当前任务栈。
 */
class SignUpActivity : AppCompatActivity() {
    private val binding by lazy { ActivitySignUpBinding.inflate(layoutInflater) }
    private lateinit var preferenceManager: PreferenceManager
    private lateinit var leanCloudService: LeanCloudService
    private var encodeImage: String ?= null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        leanCloudService = LeanCloudService(applicationContext)
        preferenceManager = PreferenceManager(applicationContext)
        setListeners()

    }

    /**
     * 事件绑定
     */
    private fun setListeners() {
        binding.textSignIn.setOnClickListener {
            onBackPressedDispatcher.onBackPressed() // 替代onBackPressed()返回
        }
        binding.buttonSignUp.setOnClickListener {
            if (isValidSignUpDetails()) {
                signUp()
            }
        }
        binding.layoutImage.setOnClickListener {
            val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            pickImage.launch(intent)
        }
    }

    /**
     * 显示 Toast 消息
     *
     * @param message 消息内容
     */
    private fun showToast(message: String) {
        Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
    }

    /**
     * 用户注册操作
     */
    private fun signUp() {
        loading(true)
        val name = binding.inputName.text.toString().trim()
        val email = binding.inputEmail.text.toString().trim()
        val password = binding.inputPassword.text.toString().trim()
        leanCloudService.signUp(name, email, password, encodeImage) { success, objectId, errorMessage ->
            loading(false)
            if (success && objectId != null) {
                preferenceManager.putBoolean(Constants.KEY_IS_SIGNED_IN, false)
                preferenceManager.putString(Constants.KEY_USER_ID, objectId)
                preferenceManager.putString(Constants.KEY_NAME, name)
                encodeImage?.let { preferenceManager.putString(Constants.KEY_IMAGE, it) }
                val intent = Intent(applicationContext, SignInActivity::class.java)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
                startActivity(intent)
                showToast("Sign up successful")
            } else {
                showToast((errorMessage ?: "Sign up failed").toString())
            }
        }
    }

    /**
     * 编码图像为Base64字符串
     *
     * @param bitmap 要编码的位图
     * @return 编码后的Base64字符串
     */
    private fun encodeImage(bitmap: Bitmap): String {
        val previewWidth = 150
        val previewHeight = bitmap.height * previewWidth / bitmap.width
        val previewBitmap = Bitmap.createScaledBitmap(bitmap, previewWidth, previewHeight, false)
        val byteArrayOutputStream = ByteArrayOutputStream()
        previewBitmap.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream)
        val bytes = byteArrayOutputStream.toByteArray()
        return Base64.encodeToString(bytes, Base64.DEFAULT)
    }


    /**
     * 添加图片操作
     */
    private val pickImage:ActivityResultLauncher<Intent> = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            val imageUri = result.data?.data
            try {
                val inputStream = contentResolver.openInputStream(imageUri!!)
                val bitmap = BitmapFactory.decodeStream(inputStream)
                binding.imageProfile.setImageBitmap(bitmap)
                binding.textAddImage.visibility = GONE
                encodeImage = encodeImage(bitmap)
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 验证用户输入的注册信息
     *
     * @return 输入是否有效
     */
    private fun isValidSignUpDetails(): Boolean {
        val name = binding.inputName.text.toString().trim()
        val email = binding.inputEmail.text.toString().trim()
        val password = binding.inputPassword.text.toString().trim()
        val confirmPassword = binding.inputConfirmPassword.text.toString().trim()
        if (encodeImage == null) {
            showToast("Please select an image")
            return false
        } else if (name.isEmpty()) {
            showToast("Please enter name")
            return false
        } else if (email.isEmpty()) {
            showToast("Please enter email")
            return false
        } else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            showToast("Please enter valid email")
            return false
        } else if (password.isEmpty()) {
            showToast("Please enter password")
            return false
        } else if (password.length < 6) {
            showToast("Password must be at least 6 characters long")
            return false
        } else if (confirmPassword.isEmpty()) {
            showToast("Please enter confirm password")
            return false
        } else if (password != confirmPassword) {
            showToast("Password and confirm password must be same")
            return false
        }
        return true
    }

    /**
     * 显示或隐藏加载进度条
     *
     * @param isLoading 是否正在加载
     */
    private fun loading(isLoading: Boolean) {
        if (isLoading) {
            binding.buttonSignUp.visibility = INVISIBLE
            binding.progressBar.visibility = VISIBLE
        } else {
            binding.buttonSignUp.visibility = VISIBLE
            binding.progressBar.visibility = INVISIBLE
        }
    }
}